#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>

#define MAXLINE   1024
#define FILE_MODE   (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) 

int main(int argc ,char * argv[]){
   int out;
   char buff[MAXLINE] = {'\0'};
   if(argc < 2){
     printf("Usage: stdout2fifo <fifo_filename>");
     exit(1);
   }

   if((mkfifo(argv[1],FILE_MODE))==-1 && errno != EEXIST) {
     printf("mkfifo error:%s\n",strerror(errno));
     exit(1);
   }

   printf("PIPE_BUF = %ld , OPEN_MAX = %ld\n",pathconf(argv[1],_PC_PIPE_BUF),sysconf(_SC_OPEN_MAX));

   out = open(argv[1],O_WRONLY,0);
   if(out < 0){
     printf("open %s error:%s\n",argv[1],strerror(errno));
     exit(1);
   }


   int n = -1;
   while( (n=read(STDOUT_FILENO,buff,MAXLINE)) >0){
     if(write(out,buff,n) != n){
        printf("write fifo error:%s\n",strerror(errno));
        close(out);
        exit(1);
     }
   }
  
   unlink(argv[1]);
   return 0;
} 
